const jwt = require('jsonwebtoken');
const {
    find
} = require('../../faas');

exports.jwt = jwt;

const expireTime = 60 * 60;

exports.signToken = (rawData, secret) => {
    return jwt.sign(rawData, secret, {
        expiresIn: expireTime
    });
};

exports.verifyToken = (token, secret) => {
    return jwt.verify(token, secret, async function (err, decoded) {
        if (err) {
            console.error(err);

            return {
                flag: false,
                msg: err
            }
        }

        console.log('decoded', decoded, typeof decoded);

        const {
            phone,
            upwd
        } = decoded;

        let r = await find('imagepic', 'auth', {
            phone,
            upwd
        });

        console.log('r', r)

        if (r.flag == true) {
            if (JSON.parse(r.data)._collections[0].upwd === decoded.upwd) {
                return {
                    flag: true,
                    msg: '验证成功'
                }
            } else {
                return {
                    flag: false,
                    msg: '登录密码不正确'
                }
            }
        } else {
            return {
                flag: false,
                msg: '登录用户未找到'
            }
        }
    });
}